import hashlib


def sign_body(body, apikey="12345678"):
    '''请求body sign签名'''
    # 列表生成式，生成key=value格式
    a = ["".join(i) for i in body.items() if i[1] and i[0] != "sign"]
    # print(a)
    # 参数名ASCII码从小到大排序
    strA = "".join(sorted(a))
    # print(strA)

    # 在strA后面拼接上apiKey得到striSignTemp字符串
    striSignTemp = strA + apikey

    # 将strSignTemp字符串转换为小写字符串后进行MD5运算

    # MD5加密
    def jiamimd5(src):
        m = hashlib.md5()
        m.update(src.encode('UTF-8'))
        return m.hexdigest()

    sign = jiamimd5(striSignTemp.lower())
    # print(sign)

    # 得到sign签名后新的body值
    # body["sign"] = sign
    # print(body)

    return sign


if __name__ == '__main__':
    apikey = "12345678"  # 验证密钥，由开发提供

    body = {
        "username": "test",
        "password": "123456",
        "mail": "",
        "sign": ""
    }
    print(sign_body(body, apikey="12345678"))
